function licenseResults = checkMBDToolboxLicenses(app)
    % checkMBDToolboxLicenses - MBD工具箱许可证检查和配置
    % 
    % 功能说明：
    %   检查MATLAB/Simulink MBD开发所需的各种工具箱许可证状态
    %   根据许可证可用性配置GUI按钮的启用/禁用状态
    %   为各功能面板添加DO-178相关的状态说明文本
    %
    % 输入参数：
    %   app - mbdWorkflowTool_Redesigned应用对象
    %
    % 输出参数：
    %   licenseResults - 包含各工具箱许可证状态的结构体
    %
    % DO-178合规性：
    %   本函数支持DO-178 Level A/B/C项目中的工具链许可证验证
    %   确保只有获得许可的工具才能在认证项目中使用
    %
    % 作者：MBD Platform Team
    % 日期：2025年9月14日
    % 版本：v2.0
    
    try
        % 定义许可证映射表
        licenseResults = struct();
        licenseResults.Polyspace_Bug_Finder = license('test', 'Polyspace_Bug_Finder');
        licenseResults.Polyspace_Code_Prover = license('test', 'Polyspace_Code_Prover');
        licenseResults.Simulink_Design_Verifier = license('test', 'Simulink_Design_Verifier'); 
        licenseResults.Simulink_Code_Inspector = license('test', 'Simulink_Code_Inspector');
        licenseResults.Simulink_Test = license('test', 'Simulink_Test');
        licenseResults.Simulink_Coder = license('test', 'Real-Time_Workshop');
        licenseResults.Simulink_Check = license('test', 'sl_verification_validation');
        licenseResults.MATLAB_Report_Generator = license('test', 'MATLAB_Report_Gen');
        
        % 存储许可证状态到应用对象
        app.LicenseStatus = licenseResults;
        
        % 配置各功能按钮和状态文本
        configurePolyspaceBugFinderFeature(app, licenseResults.Polyspace_Bug_Finder);
        configurePolyspaceCodeProverFeature(app, licenseResults.Polyspace_Code_Prover);
        configureSLDVFeature(app, licenseResults.Simulink_Design_Verifier);
        configureCodeInspectorFeature(app, licenseResults.Simulink_Code_Inspector);
        configureTestingFeatures(app, licenseResults.Simulink_Test);
        configureCodeGenerationFeature(app, licenseResults.Simulink_Coder);
        configureCodeMetricsFeature(app, licenseResults.Polyspace_Bug_Finder);  % 代码指标需要Polyspace
        configureModelAdvisorFeature(app, licenseResults.Simulink_Check);
        configureReportGenerationFeature(app, licenseResults.MATLAB_Report_Generator);
        configureTestAuthoringFeature(app);  % 测试编写工具 - 无需许可证
        configureDocumentationFeature(app); % 文档查看功能 - 无需许可证
        configureModelChecklistFeature(app); % 模型检查清单 - 无需许可证
        
        % 输出许可证检查摘要
        fprintf('\n=== MBD工具箱许可证检查结果 ===\n');
        printLicenseStatus('Polyspace Bug Finder', licenseResults.Polyspace_Bug_Finder);
        printLicenseStatus('Polyspace Code Prover', licenseResults.Polyspace_Code_Prover);
        printLicenseStatus('Simulink Design Verifier', licenseResults.Simulink_Design_Verifier);
        printLicenseStatus('Simulink Code Inspector', licenseResults.Simulink_Code_Inspector);
        printLicenseStatus('Simulink Test', licenseResults.Simulink_Test);
        printLicenseStatus('Simulink Coder', licenseResults.Simulink_Coder);
        printLicenseStatus('Simulink Check', licenseResults.Simulink_Check);
        printLicenseStatus('MATLAB Report Generator', licenseResults.MATLAB_Report_Generator);
        fprintf('================================\n\n');
        
    catch ME
        % 许可证检查失败时的处理
        warning(ME.identifier, 'MBD工具箱许可证检查过程中出现错误: %s', ME.message);
        % 默认禁用所有高级功能
        disableAllAdvancedFeatures(app);
        licenseResults = struct(); % 返回空结构体
    end
end

function configurePolyspaceBugFinderFeature(app, hasLicense)
    % 配置Polyspace Bug Finder静态分析功能（包含Bug Finder和Code Standards）
    if hasLicense
        app.RunBugFinderButton.Enable = 'on';
        app.RunCodeStandardsButton.Enable = 'on';
        statusText = 'Polyspace Bug Finder：检测运行时错误、死代码、MISRA C合规性检查。DO-178 Level A/B/C代码质量分析必备工具。';
    else
        app.RunBugFinderButton.Enable = 'off';
        app.RunCodeStandardsButton.Enable = 'off';
        statusText = 'Polyspace Bug Finder：检测运行时错误、死代码、MISRA C合规性检查。DO-178 Level A/B/C代码质量分析必备工具。(license required)';
    end
    % 使用统一的动态标签创建方法
    createFeatureStatusLabel(app, 'CodeAnalysisPanel', statusText);
end

function configurePolyspaceCodeProverFeature(app, hasLicense)
    % 配置Polyspace Code Prover形式化验证功能
    if hasLicense
        app.RunCodeProverButton.Enable = 'on';
        statusText = 'Polyspace Code Prover：形式化验证代码质量，证明代码无运行时错误。DO-178 Level A形式化方法验证工具。';
    else
        app.RunCodeProverButton.Enable = 'off';
        statusText = 'Polyspace Code Prover：形式化验证代码质量，证明代码无运行时错误。DO-178 Level A形式化方法验证工具。(license required)';
    end
    % Code Prover的状态文本也添加到CodeAnalysisPanel（不会覆盖，会追加）
    % 注意：由于createFeatureStatusLabel会动态添加行，多次调用不会覆盖
end

function configureSLDVFeature(app, hasLicense)
    % 配置SLDV设计验证功能
    if hasLicense
        app.RunSLDVButton.Enable = 'on';
        statusText = 'SLDV设计验证：自动生成测试用例，检测设计错误。满足DO-178 Level A验证要求。';
    else
        app.RunSLDVButton.Enable = 'off';
        statusText = 'SLDV设计验证：自动生成测试用例，检测设计错误。满足DO-178 Level A验证要求。(license required)';
    end
    createFeatureStatusLabel(app, 'SLDVPanel', statusText);
end

function configureCodeInspectorFeature(app, hasLicense)
    % 配置代码检查器功能
    if hasLicense
        app.RunCodeInspectorButton.Enable = 'on';
        statusText = '代码检查器：验证生成代码与模型一致性。DO-178要求的代码审查工具。';
    else
        app.RunCodeInspectorButton.Enable = 'off';
        statusText = '代码检查器：验证生成代码与模型一致性。DO-178要求的代码审查工具。(license required)';
    end
    createFeatureStatusLabel(app, 'CodeInspectionPanel', statusText);
end

function configureTestingFeatures(app, hasLicense)
    % 配置测试相关功能
    if hasLicense
        enableStatus = 'on';
    else
        enableStatus = 'off';
    end
    app.RunHLRTestButton.Enable = enableStatus;
    app.RunLLRTestButton.Enable = enableStatus;
    app.MergeCoverageButton.Enable = enableStatus;
    app.GenerateCoverageReportButton.Enable = enableStatus;
    
    if hasLicense
        hlrStatusText = 'HLR测试：高层需求测试验证。DO-178要求的需求驱动测试。';
        llrStatusText = 'LLR测试：低层需求测试验证。DO-178详细设计验证必备。';
        coverageStatusText = '覆盖率分析：代码覆盖率统计。DO-178 Level A/B/C测试充分性证明。';
    else
        hlrStatusText = 'HLR测试：高层需求测试验证。DO-178要求的需求驱动测试。(license required)';
        llrStatusText = 'LLR测试：低层需求测试验证。DO-178详细设计验证必备。(license required)';
        coverageStatusText = '覆盖率分析：代码覆盖率统计。DO-178 Level A/B/C测试充分性证明。(license required)';
    end
    
    createFeatureStatusLabel(app, 'HLRTestPanel', hlrStatusText);
    createFeatureStatusLabel(app, 'LLRTestPanel', llrStatusText);
    createFeatureStatusLabel(app, 'CoveragePanel', coverageStatusText);
end

function configureCodeGenerationFeature(app, hasLicense)
    % 配置代码生成功能
    if hasLicense
        app.GenerateCodeButton.Enable = 'on';
        statusText = '代码生成：从Simulink模型自动生成C/C++代码。DO-178认证的代码生成工具。';
    else
        app.GenerateCodeButton.Enable = 'off';
        statusText = '代码生成：从Simulink模型自动生成C/C++代码。DO-178认证的代码生成工具。(license required)';
    end
    createFeatureStatusLabel(app, 'CodeGenPanel', statusText);
end

function configureCodeMetricsFeature(app, hasLicense)
    % 配置代码质量指标功能
    if hasLicense
        app.ComputeCodeMetricsButton.Enable = 'on';
        statusText = '代码质量指标：基于Polyspace分析的代码复杂度、质量评估。DO-178代码质量验证必备工具。';
    else
        app.ComputeCodeMetricsButton.Enable = 'off';
        statusText = '代码质量指标：基于Polyspace分析的代码复杂度、质量评估。DO-178代码质量验证必备工具。(license required)';
    end
    createFeatureStatusLabel(app, 'CodeQualityPanel', statusText);
end

function configureModelAdvisorFeature(app, hasLicense)
    % 配置Model Advisor功能
    if hasLicense
        app.RunModelAdvisorButton.Enable = 'on';
        app.ComputeModelMetricsButton.Enable = 'on';
        advisorStatusText = 'Model Advisor：模型标准检查。DO-178建模标准合规性验证。';
        metricsStatusText = '模型指标：复杂度、可读性分析。DO-178软件复杂性评估。';
    else
        app.RunModelAdvisorButton.Enable = 'off';
        app.ComputeModelMetricsButton.Enable = 'off';
        advisorStatusText = 'Model Advisor：模型标准检查。DO-178建模标准合规性验证。(license required)';
        metricsStatusText = '模型指标：复杂度、可读性分析。DO-178软件复杂性评估。(license required)';
    end
    createFeatureStatusLabel(app, 'ModelStandardsPanel', advisorStatusText);
    createFeatureStatusLabel(app, 'ModelMetricsPanel', metricsStatusText);
end

function configureReportGenerationFeature(app, hasLicense)
    % 配置报告生成功能
    if hasLicense
        app.GenerateSDDButton.Enable = 'on';
        app.SDDReportButton.Enable = 'on';
        statusText = 'SDD报告生成：软件设计描述文档。DO-178 Level A/B/C必需交付件。';
    else
        app.GenerateSDDButton.Enable = 'off';
        app.SDDReportButton.Enable = 'off';
        statusText = 'SDD报告生成：软件设计描述文档。DO-178 Level A/B/C必需交付件。(license required)';
    end
    createFeatureStatusLabel(app, 'ReportGenerationPanel', statusText);
    createFeatureStatusLabel(app, 'ModelReportsPanel', statusText);
end

function configureTestAuthoringFeature(app)
    % 配置测试编写工具功能 - 无需许可证
    app.TestAuthoringToolButton.Enable = 'on';  % 始终启用
    statusText = '测试编写工具：打开测试用例编写和管理界面。支持HLR/LLR测试场景设计。';
    createFeatureStatusLabel(app, 'TestManagementPanel', statusText);
end

function configureDocumentationFeature(app)
    % 配置文档查看功能 - 无需许可证
    app.ViewDocumentationButton.Enable = 'on';  % 始终启用
    statusText = sprintf('文档中心：访问用户指南、API文档和帮助资源。\n包含DO-178流程指导和最佳实践。');
    createFeatureStatusLabel(app, 'DocumentationPanel', statusText);
end

function configureModelChecklistFeature(app)
    % 配置模型检查清单功能 - 无需许可证
    app.CreateModelChecklistButton.Enable = 'on';  % 始终启用
    app.OpenModelChecklistButton.Enable = 'on';    % 始终启用
    statusText = '模型检查清单：创建和管理模型评审检查清单。DO-178模型审查质量保证工具。';
    createFeatureStatusLabel(app, 'ModelChecklistPanel', statusText);
end

function disableAllAdvancedFeatures(app)
    % 许可证检查失败时禁用所有高级功能
    % Polyspace按钮
    app.RunBugFinderButton.Enable = 'off';
    app.RunCodeStandardsButton.Enable = 'off';
    app.RunCodeProverButton.Enable = 'off';
    % 其他分析按钮
    app.RunSLDVButton.Enable = 'off';
    app.RunCodeInspectorButton.Enable = 'off';
    app.RunHLRTestButton.Enable = 'off';
    app.RunLLRTestButton.Enable = 'off';
    app.MergeCoverageButton.Enable = 'off';
    app.GenerateCodeButton.Enable = 'off';
    app.ComputeCodeMetricsButton.Enable = 'off';
    app.RunModelAdvisorButton.Enable = 'off';
    app.ComputeModelMetricsButton.Enable = 'off';
    app.GenerateSDDButton.Enable = 'off';
    app.SDDReportButton.Enable = 'off';
    app.GenerateCoverageReportButton.Enable = 'off';
end


function createFeatureStatusLabel(app, panelName, statusText)
    % 为指定面板创建功能状态标签
    try
        % 获取对应的panel
        panelHandle = app.(panelName);
        if isvalid(panelHandle)
            % 查找panel内的网格布局
            grids = findall(panelHandle, 'Type', 'uigridlayout');
            if ~isempty(grids)
                grid = grids(1); % 取第一个网格布局
                
                % 创建状态标签，放在网格的最后一行
                statusLabel = uilabel(grid);
                statusLabel.Text = statusText;
                statusLabel.FontSize = 9;
                statusLabel.FontColor = [0.5 0.5 0.5];
                statusLabel.WordWrap = 'on';
                statusLabel.VerticalAlignment = 'top';
                
                % 动态添加新行，将说明文字放在Panel底部
                grid.RowHeight = [grid.RowHeight, {'fit'}];
                newRowIndex = length(grid.RowHeight);
                
                % 根据不同面板调整列跨度
                switch panelName
                    case {'SLDVPanel', 'CodeInspectionPanel', 'ModelStandardsPanel', ...
                          'ModelMetricsPanel', 'ModelReportsPanel', 'CodeQualityPanel', ...
                          'CodeAnalysisPanel', 'ModelChecklistPanel'}
                        % 2列布局的面板，横跨两列
                        statusLabel.Layout.Row = newRowIndex;
                        statusLabel.Layout.Column = [1, 2];
                    case {'HLRTestPanel', 'LLRTestPanel'}
                        % 测试面板，横跨两列
                        statusLabel.Layout.Row = newRowIndex;
                        statusLabel.Layout.Column = [1, 2];
                    case 'CoveragePanel'
                        % 覆盖率面板，单列布局
                        statusLabel.Layout.Row = newRowIndex;
                        statusLabel.Layout.Column = 1;
                    case 'CodeGenPanel'
                        % 代码生成面板，单列布局
                        statusLabel.Layout.Row = newRowIndex;
                        statusLabel.Layout.Column = 1;
                    case {'TestManagementPanel', 'DocumentationPanel'}
                        % 单列布局的面板
                        statusLabel.Layout.Row = newRowIndex;
                        statusLabel.Layout.Column = 1;
                    case 'ReportGenerationPanel'
                        % 报告面板，横跨两列
                        statusLabel.Layout.Row = newRowIndex;
                        statusLabel.Layout.Column = [1, 2];
                    otherwise
                        % 默认情况：单列
                        statusLabel.Layout.Row = newRowIndex;
                        statusLabel.Layout.Column = 1;
                end
            end
        end
    catch ME
        % 静默处理面板查找失败的情况
        warning('无法为面板 %s 创建状态标签: %s', panelName, ME.message);
    end
end

function printLicenseStatus(toolboxName, hasLicense)
    % 打印许可证状态信息
    if hasLicense
        status = '✓ 可用';
    else
        status = '✗ 不可用';
    end
    fprintf('  %s: %s\n', toolboxName, status);
end
